package com.system.test.thread;

import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池小结：
 * 
 * @author kaifa002
 *
 */
public class ThreadPoolSnippet {

	public static void main(String[] args) {
		
		 Thread t2 = new Thread();  
        //输出：sun.misc.Launcher$AppClassLoader@43be2d65 新线程没有设置ContextClassLoader，将继承其父线程的上下文类加载器 
        System.out.println(t2.getContextClassLoader());  
        //输出：null 因为Thread.class 是引导类加载加载的，所以其父类加载器 是为空 
        System.out.println(t2.getClass().getClassLoader());  
	        
		// 可用的处理器核心
		int N_CPUS = Runtime.getRuntime().availableProcessors();
		System.out.println(N_CPUS);
		
		// myThreadPoolExecutor();
		ThreadPoolExecutor threadPool = myThreadPoolExecutorRejected();
		// 执行任务
		for (int i = 1; i < 15; i++) {
			threadPool.execute(new MyRunnable(i+""));
		}
	}

	public static void myThreadPoolExecutor() {
		// 创建线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
		// 执行任务
		for (int i = 0; i < 15; i++) {
			final int index = i;
			threadPool.execute(() -> {
				System.out.println(index + " 被执行,线程名:" + Thread.currentThread().getName());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}
	}
	
	/**
	 * 自定义拒绝策略
	 * @return
	 */
	public static ThreadPoolExecutor myThreadPoolExecutorRejected() {
		// 创建线程池
		return new ThreadPoolExecutor(2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10),
			new RejectedExecutionHandler() {
				@Override
				public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
					// 从Runnable中获取任务信息
					MyRunnable myRunnable = (MyRunnable) r;
					System.out.println("我是自定义拒绝策略~，任务编号："+ myRunnable.getId() +"，超出容量去存到redis或者数据库啊！");
				}
			}
		);
	}

	// ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1), new ThreadPoolExecutor.DiscardPolicy());

}

class MyRunnable implements Runnable {

	private String id;
	
	public MyRunnable() {
		
	}
	
	public MyRunnable(String id) {
		this.id = id;
	}

	@Override
	public void run() {
		// System.out.println(index + " 被执行,线程名:" + Thread.currentThread().getName());
		System.out.println(id + " 当前任务被执行,执行时间:" + new Date() + " 执行线程:" + Thread.currentThread().getName());
		try {
			// 等待 1s
			TimeUnit.SECONDS.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}
}
